<template>
  <div class="ImgPicker" :style="'width:' + Width + '; height:' + Height + ';'">
    <div v-if="imageUrl!=''" class="ImageResult" :style="'width:' + Width + '; height:' + Height + ';'">
      <slot></slot>
      <el-image class="img img-mark" :src="MarkImageUrl" :fit="'contain'" v-if="MarkImageUrl"  @click="$emit('imageClick', imageUrl)" ></el-image>
      <el-image class="img" :src="imageUrl"  :fit="'contain'" @click="$emit('imageClick', imageUrl)" ></el-image>
      <div class="clearBtn" @click="clearImg">X</div>
      <div class="doodleBtn" v-if="Doodle" @click="doodleImg">涂抹</div>
    </div>
    <div v-else class="ImageResult" :style="'width:' + Width + '; height:' + Height + ';'" @click="showImgSelecter=true">
      <div class="pickerTipsTxt">{{ TipsTxt }}</div>
    </div>
    <el-drawer class="ImgSelecter" title="模特换装" v-model="showImgSelecter" direction="rtl" size="60%" :with-header="false">
      <div class="drawerContent">
        <div class="uploaderWrap">
          <el-upload
            class="uploader"
            drag
            :action="ToPlatform.toLowerCase() =='comfyui'?uploadAddressComfyui:uploadAddress"
            :limit="1"
            :name="KeyName"
            :headers="ToPlatform.toLowerCase() =='comfyui'?uploadAddressComfyuiHeader:uploadAddressHeader"
            :show-file-list="false"
            :on-success ="uploaded"
            :on-change="uploaderValueChange"
            v-model:file-list="fileList"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              把文件拖放进当前位置或 <em>点击上传</em>
            </div>
          </el-upload>
        </div>
        <div class="libraryWrap">
          <Library ref="library" class="libraryObj" :selectMode="true" @selected="setImgFromLibrary"></Library>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
 
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.ImgPicker .ImageResult{ position: relative; background: #eee; border-radius: 18px; overflow:hidden; padding: 0; box-sizing: border-box; display: flex; justify-content: center; align-items: center; cursor: pointer;}
.ImgPicker .ImageResult .img{position: absolute;width: 100%; height: 100%;}
.ImgPicker .ImageResult .img-mark{z-index: 2; opacity: 0.6;}
/* .ImgPicker .ImageResult .img-mark::before{content:''; position: absolute;width: 100%;height: 100%;} */
.ImgPicker .ImageResult .img-mark img{user-select: none; -webkit-user-drag: none;user-drag: none;}
.ImgPicker .ImageResult .pickerTipsTxt{ color: #999; }
.ImgPicker .ImageResult .clearBtn{ position: absolute; right: 8px; top: 8px; z-index: 2; width: 20px; height: 20px; border-radius: 14px; text-align: center; line-height: 20px; background: #2c3e50; font-size: 12px; color: #fff;}
.ImgPicker .ImageResult .doodleBtn{
  position: absolute; left: 8px; top: 8px; height: 20px; padding: 0 8px; border-radius: 14px; text-align: center; line-height: 20px; background: #2c3e50; font-size: 12px; color: #fff; z-index: 9;
}
.libraryObj{width: 100%; flex: 1;}
.ImgSelecter .drawerContent{ width:100%; height:100%; display: flex; flex-direction: column; overflow: hidden;}
.ImgSelecter .drawerContent .uploaderWrap{height: 200px; width: 100%; margin-bottom: 18px; padding-bottom: 18px; border-bottom: 1px solid #eee; overflow: hidden;}
.ImgSelecter .drawerContent .uploaderWrap .uploader{ height: 100%; }
.ImgSelecter .drawerContent .libraryWrap{ flex: 1; width: 100%; overflow: hidden;}
.ImgSelecter .uploaderWrap .libraryWrap .libraryObj{height: 100%; overflow-y: auto;}
</style>

<script>
import Library from '../layout/library.vue'
import WebAPI from '@/unit/api';
import OS from '@/unit/OS';
import WebRequest from '../../unit/request.js'
import { ref } from 'vue';


export default {
  name: 'ImagePicker',
  components:{ Library },
  props: {
    TipsTxt: {
      type:String,
      default: '请上传图片'
    },
    Width:{
      type:String,
      default: '240px'
    },
    Height:{
      type:String,
      default: '240px'
    },
    ToPlatform:{
      type:String,
      default:'prometheus'
    },
    // 遮罩图
    MarkImageUrl: {
      type:String,
      default:null
    },
    // 默认图片：图片url，可改变
    DefaultImageUrl:{
      type:String,
      default:''
    },
    // 是否显示“涂抹”按钮
    Doodle: {
      type: Boolean,
      default: false
    },
    // 上传时的key值
    KeyName: {
      type: String,
      default: 'file'
    },
    // 上传时的key值
    UploadPath: {
      type: String,
      default: null
    },
    // 成功后的处理模式：此为针对新接口做的临时处理
    SuccessType: {
      type: String,
      default: null
    },
  },
  data () {
    return {
      uploadAddress:WebAPI.UploadImage,
      uploadAddressHeader:{
        Token:OS.GetToken()
      }, 
      uploadAddressComfyui:WebAPI.UploadImageToComfyui,
      uploadAddressComfyuiHeader:{
      },
      imageUrl:'',
      showImgSelecter:false,
      fileList:[],
      uploadImgSrc:'',
      fileName:'',
      sourceImageDepotId:''
    }
  },
  mounted() {
    // 重新设置上传路径
    if(this.UploadPath || this.UploadPath != '') {
      this.uploadAddress = this.UploadPath
    }
    /*var url = 'http://vibktprfx-prod-prod-aic-vd-cn-shanghai.oss-cn-shanghai.aliyuncs.com/eas-cloth_segmentation/2024-02-18/e39d1d8d-e88f-4a8c-a727-4a7b885eedc3/clothes_image.png?OSSAccessKeyId=LTAI4G45u1DBkiaLMWCLJwrF&Expires=1708251523&Signature=nHDDUw6wBPnAWNbDLqutcWdGFso%3D'+'&a='+Math.floor(Math.random() * 1000000)
    var self = this
    self.imageUrl = url*/
    /*console.log(self.imageUrl)
    OS.SwapImgWBColor(url,function(base64){
      console.log('callback')
      self.imageUrl = base64
    })*/
  },
  watch: {
    DefaultImageUrl: {
      handler() {
        this.imageUrl = this.DefaultImageUrl;
        if (this.DefaultImageUrl && this.DefaultImageUrl !== '' ) {
          this.setNowData(this.imageUrl, null);
        } else {
          this.clearImg()
        }
      },
      immediate: true
    },
  },
  methods: {
    setNowData (url,file,id) {
      var self = this;
      self.imageUrl = url;
      self.fileName = file;
      self.sourceImageDepotId = id;
      self.$emit('change',{imageUrl: url, fileName:file,sourceImageDepotId:id});
      self.showImgSelecter = false;
    },
    setImgFromLibrary(e){
      var self = this
      /*console.log('setImgFromLibrary',e)
      if(self.ToPlatform.toLowerCase() == 'comfyui'){
        WebRequest.UploadImageToComfyui({
          imageUrl: e.imageUrl,
          callback:res => {
            console.log('upload success', res)
            if(res.errCode == 10000){
              //self.fileName = res.data.name
              self.$emit('change',{imageUrl: e.imageUrl,fileName:res.data.name});
            }else{
              console.log('upload error', res)
            }
          },
          error:res => {
            console.log('upload call error:', res)
          }
        })
      }else{
        self.setNowData(e.imageUrl)
      }*/
      console.log(e);
      self.setNowData(e.imageUrl,"",e.id)
    },
    clearImg(){
      this.setNowData('')
      this.$emit('clear',true)
    },
    uploaderValueChange(file,fileLists){
      //console.log(document.getElementsByClassName('el-upload__input'))
      //this.uploadImgSrc = document.getElementsByClassName('el-upload__input')[0].value;
      this.uploadImgSrc = URL.createObjectURL(file.raw);
    },
    uploaded(e,file){
      //console.log('uploaded:', e, file);
      console.log('uploaded:', e);
      console.log(this.fileList);
      this.fileList = [];
      //this.setNowData(this.uploadImgSrc);
      if(this.ToPlatform.toLowerCase() == 'comfyui'){
        this.setNowData(this.uploadImgSrc,e.data.name);
      }else{
        // 新接口处理
        if(this.SuccessType == 'New-ComfyUI') {
          this.setNowData(null, e.name);
        } 
        
        else if(e.errCode == 10000){
          this.setNowData(e.data.rows[0].sourceUrl);
        }else{
          console.log('上传图片失败')
        }
      }
    },
    doodleImg() {
      this.$emit('doodleImg', this.imageUrl)
    },
  }
}
</script>

